// TabWorkspace Manager - 后台服务工作者

// 扩展安装或启动时的初始化
chrome.runtime.onInstalled.addListener((details) => {
  console.log('TabWorkspace Manager 已安装/更新');
  
  if (details.reason === 'install') {
    // 首次安装时的初始化
    initializeExtension();
  } else if (details.reason === 'update') {
    // 更新时的处理
    handleExtensionUpdate(details.previousVersion);
  }
});

// 初始化扩展
async function initializeExtension() {
  try {
    // 检查存储中是否已有数据
    const result = await chrome.storage.local.get(['workspaces', 'settings']);
    
    if (!result.workspaces) {
      // 初始化工作区数据
      await chrome.storage.local.set({
        workspaces: [],
        settings: {
          version: '0.1.0',
          defaultSaveMode: 'links-only',
          autoCleanup: false,
          maxWorkspaces: 100
        }
      });
      console.log('扩展数据初始化完成');
    }
    
    // 设置扩展图标
    updateExtensionIcon();
    
  } catch (error) {
    console.error('初始化扩展失败:', error);
  }
}

// 处理扩展更新
async function handleExtensionUpdate(previousVersion) {
  try {
    console.log(`从版本 ${previousVersion} 更新到当前版本`);
    
    // 这里可以添加数据迁移逻辑
    const result = await chrome.storage.local.get(['settings']);
    if (result.settings) {
      result.settings.version = '0.1.0';
      await chrome.storage.local.set({ settings: result.settings });
    }
    
  } catch (error) {
    console.error('处理扩展更新失败:', error);
  }
}

// 更新扩展图标
function updateExtensionIcon() {
  chrome.action.setIcon({
    path: 'icons/workspace.png'
  });
}

// 监听来自content script或popup的消息
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  console.log('收到消息:', request);
  
  switch (request.action) {
    case 'getWorkspaces':
      handleGetWorkspaces(sendResponse);
      return true; // 保持消息通道开放
      
    case 'saveWorkspace':
      handleSaveWorkspace(request.data, sendResponse);
      return true;
      
    case 'deleteWorkspace':
      handleDeleteWorkspace(request.workspaceId, sendResponse);
      return true;
      
    case 'restoreWorkspace':
      handleRestoreWorkspace(request.workspaceId, request.newWindow, sendResponse);
      return true;
      
    case 'getTabsCount':
      handleGetTabsCount(sendResponse);
      return true;
      
    default:
      console.warn('未知的消息类型:', request.action);
      sendResponse({ success: false, error: '未知的消息类型' });
  }
});

// 获取工作区列表
async function handleGetWorkspaces(sendResponse) {
  try {
    const result = await chrome.storage.local.get(['workspaces']);
    sendResponse({ 
      success: true, 
      data: result.workspaces || [] 
    });
  } catch (error) {
    console.error('获取工作区失败:', error);
    sendResponse({ 
      success: false, 
      error: error.message 
    });
  }
}

// 保存工作区
async function handleSaveWorkspace(workspaceData, sendResponse) {
  try {
    const result = await chrome.storage.local.get(['workspaces']);
    const workspaces = result.workspaces || [];
    
    // 检查工作区名称是否重复
    const isDuplicate = workspaces.some(ws => ws.name === workspaceData.name);
    if (isDuplicate) {
      sendResponse({ 
        success: false, 
        error: '工作区名称已存在' 
      });
      return;
    }
    
    // 添加新工作区
    workspaces.push(workspaceData);
    
    // 限制工作区数量
    const maxWorkspaces = 100;
    if (workspaces.length > maxWorkspaces) {
      workspaces.splice(0, workspaces.length - maxWorkspaces);
    }
    
    await chrome.storage.local.set({ workspaces });
    
    sendResponse({ 
      success: true, 
      message: '工作区保存成功' 
    });
    
    // 更新扩展徽章
    updateBadge(workspaces.length);
    
  } catch (error) {
    console.error('保存工作区失败:', error);
    sendResponse({ 
      success: false, 
      error: error.message 
    });
  }
}

// 删除工作区
async function handleDeleteWorkspace(workspaceId, sendResponse) {
  try {
    const result = await chrome.storage.local.get(['workspaces']);
    const workspaces = result.workspaces || [];
    
    const index = workspaces.findIndex(ws => ws.id === workspaceId);
    if (index === -1) {
      sendResponse({ 
        success: false, 
        error: '工作区不存在' 
      });
      return;
    }
    
    workspaces.splice(index, 1);
    await chrome.storage.local.set({ workspaces });
    
    sendResponse({ 
      success: true, 
      message: '工作区删除成功' 
    });
    
    // 更新扩展徽章
    updateBadge(workspaces.length);
    
  } catch (error) {
    console.error('删除工作区失败:', error);
    sendResponse({ 
      success: false, 
      error: error.message 
    });
  }
}

// 恢复工作区
async function handleRestoreWorkspace(workspaceId, newWindow, sendResponse) {
  try {
    const result = await chrome.storage.local.get(['workspaces']);
    const workspaces = result.workspaces || [];
    
    const workspace = workspaces.find(ws => ws.id === workspaceId);
    if (!workspace) {
      sendResponse({ 
        success: false, 
        error: '工作区不存在' 
      });
      return;
    }
    
    if (workspace.tabs.length === 0) {
      sendResponse({ 
        success: false, 
        error: '工作区中没有标签页' 
      });
      return;
    }
    
    // 恢复标签页
    if (newWindow) {
      // 在新窗口中恢复
      const window = await chrome.windows.create({
        url: workspace.tabs[0].url,
        focused: true
      });
      
      // 添加其余标签页
      for (let i = 1; i < workspace.tabs.length; i++) {
        await chrome.tabs.create({
          windowId: window.id,
          url: workspace.tabs[i].url,
          active: false
        });
      }
    } else {
      // 在当前窗口中恢复
      for (const tab of workspace.tabs) {
        await chrome.tabs.create({
          url: tab.url,
          active: false
        });
      }
    }
    
    sendResponse({ 
      success: true, 
      message: `成功恢复工作区 "${workspace.name}"` 
    });
    
  } catch (error) {
    console.error('恢复工作区失败:', error);
    sendResponse({ 
      success: false, 
      error: error.message 
    });
  }
}

// 获取当前标签页数量
async function handleGetTabsCount(sendResponse) {
  try {
    const tabs = await chrome.tabs.query({ currentWindow: true });
    const validTabs = tabs.filter(tab => isValidTab(tab));
    
    sendResponse({ 
      success: true, 
      count: validTabs.length 
    });
  } catch (error) {
    console.error('获取标签页数量失败:', error);
    sendResponse({ 
      success: false, 
      error: error.message 
    });
  }
}

// 验证标签页是否有效
function isValidTab(tab) {
  const invalidProtocols = ['chrome://', 'chrome-extension://', 'edge://', 'about:'];
  return !invalidProtocols.some(protocol => tab.url.startsWith(protocol));
}

// 更新扩展徽章
function updateBadge(count) {
  if (count > 0) {
    chrome.action.setBadgeText({ 
      text: count > 99 ? '99+' : count.toString() 
    });
    chrome.action.setBadgeBackgroundColor({ 
      color: '#007bff' 
    });
  } else {
    chrome.action.setBadgeText({ text: '' });
  }
}

// 监听标签页变化，更新当前标签页数量
chrome.tabs.onCreated.addListener(() => {
  notifyTabsCountChange();
});

chrome.tabs.onRemoved.addListener(() => {
  notifyTabsCountChange();
});

chrome.tabs.onUpdated.addListener(() => {
  notifyTabsCountChange();
});

// 通知popup标签页数量变化
async function notifyTabsCountChange() {
  try {
    const tabs = await chrome.tabs.query({ currentWindow: true });
    const validTabs = tabs.filter(tab => isValidTab(tab));
    
    // 向popup发送消息（如果popup是打开的）
    chrome.runtime.sendMessage({
      action: 'tabsCountChanged',
      count: validTabs.length
    }).catch(() => {
      // popup可能没有打开，忽略错误
    });
  } catch (error) {
    // 忽略错误
  }
}

// 监听窗口焦点变化
chrome.windows.onFocusChanged.addListener((windowId) => {
  if (windowId !== chrome.windows.WINDOW_ID_NONE) {
    notifyTabsCountChange();
  }
});

// 定期清理过期数据（可选功能）
setInterval(async () => {
  try {
    const result = await chrome.storage.local.get(['settings']);
    if (result.settings && result.settings.autoCleanup) {
      await cleanupOldWorkspaces();
    }
  } catch (error) {
    console.error('清理数据失败:', error);
  }
}, 24 * 60 * 60 * 1000); // 每24小时执行一次

// 清理旧工作区
async function cleanupOldWorkspaces() {
  try {
    const result = await chrome.storage.local.get(['workspaces']);
    const workspaces = result.workspaces || [];
    
    // 删除30天前的工作区
    const thirtyDaysAgo = new Date();
    thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30);
    
    const filteredWorkspaces = workspaces.filter(ws => {
      const createdDate = new Date(ws.createdAt);
      return createdDate > thirtyDaysAgo;
    });
    
    if (filteredWorkspaces.length !== workspaces.length) {
      await chrome.storage.local.set({ workspaces: filteredWorkspaces });
      console.log(`清理了 ${workspaces.length - filteredWorkspaces.length} 个过期工作区`);
    }
  } catch (error) {
    console.error('清理旧工作区失败:', error);
  }
}

// 处理扩展卸载
chrome.runtime.onSuspend.addListener(() => {
  console.log('TabWorkspace Manager 正在卸载');
});

// 错误处理
chrome.runtime.onStartup.addListener(() => {
  console.log('TabWorkspace Manager 启动');
  updateExtensionIcon();
});

// 初始化徽章
chrome.storage.local.get(['workspaces']).then(result => {
  const workspaces = result.workspaces || [];
  updateBadge(workspaces.length);
}).catch(error => {
  console.error('初始化徽章失败:', error);
});